<template>
	<view class="edit-container">
		<!-- 顶栏 -->
		<view class="top-bar fixed">
			<view class="top-bar-content">
				<i class="ri-arrow-left-line back-icon" @click="onBack"></i>
				<text class="edit-title">编辑动态</text>
				<button class="publish-button" @click="onPublish">发布</button>
			</view>
		</view>

		<!-- 编辑内容 -->
		<view class="content">
			<input v-model="contextTitle" placeholder="请输入标题..." class="content-title" />
			<up-divider></up-divider>
			<textarea v-model="contentText" class="content-textarea" placeholder="请输入内容..." maxlength="1000" @input="onContentInput"></textarea>
			<text class="char-counter">{{ contentTextLength }}/1000</text>

			<!-- 图文动态：上传图片 -->
			<view v-if="dynamicType === 'image'" class="upload-section">
				<view class="image-grid">
					<view v-for="(img, index) in uploadedImages" :key="index" class="image-item" @click="onPreviewImage(index)">
						<image :src="img" mode="aspectFill" class="uploaded-image" />
						<i class="ri-close-circle-line remove-icon" @click.stop="onRemoveImage(index)"></i>
					</view>
					<view v-if="uploadedImages.length < 9" class="add-image-button" @click="onAddImage">
						<view class="add-image-content">
							<i class="ri-add-line add-icon"></i>
							<text class="add-text">添加图片</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 视频动态：上传视频 -->
			<view v-if="dynamicType === 'video'" class="upload-section">
				<view v-if="!uploadedVideo" class="upload-button light-grey-button" @click="onAddVideo">
					<i class="ri-add-line"></i>
					添加视频
				</view>
				<view v-if="uploadedVideo" class="video-item">
					<video :src="uploadedVideo" controls class="uploaded-video" />
					<i class="ri-close-circle-line remove-icon" @click="onRemoveVideo"></i>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			dynamicType: '', // 动态类型：'article'、'image'、'video'
			contextTitle: '', // 标题
			contentText: '', // 内容
			uploadedImages: [], // 上传的图片列表
			uploadImages: [], // 上传的图片列表（用于上传到服务器）
			uploadedVideo: '', // 上传的视频
			uploadVideo: '', // 上传的视频（用于上传到服务器）
			uploading: false, // 上传状态
			contentTextLength: 0 // 内容字数统计
		};
	},
	methods: {
		onBack() {
			// 返回上一个页面
			uni.navigateBack();
		},
		onPublish() {
			this.$api
				.publishCommunity({
					candidateId: uni.getStorageSync('user').candidateId,
					communityTitle: this.contextTitle,
					communityType: this.dynamicType,
					communityContent: this.contentText,
					imagePath: this.uploadImages.toString(),
					videoPath: this.uploadVideo
				})
				.then(() => {
					uni.showToast({
						title: '发布成功',
						icon: 'success'
					});
					uni.navigateBack();
				});
		},
		onContentInput() {
			// 更新字数统计
			this.contentTextLength = this.contentText.length;
			if (this.contentTextLength > 1000) {
				this.contentText = this.contentText.slice(0, 1000); // 限制输入为1000字
				this.contentTextLength = 1000; // 更新字数统计为1000
			}
		},
		async onAddImage() {
			if (this.uploadedImages.length < 9) {
				try {
					const res = await uni.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						sourceType: ['album', 'camera']
					});
					const filePath = res.tempFilePaths[0];
					this.uploading = true;
					setTimeout(() => {
						this.uploading = false;
					}, 1000); // 模拟上传进度
					const uploadRes = await uni.uploadFile({
						url: 'api/recruit-fileUpload/files/upload',
						filePath,
						name: 'file'
					});

					// 获取返回数据
					const response = JSON.parse(uploadRes.data);
					this.uploadedImages.push(response.url); // 用于展示完整图片地址
					const relativePath = response.relativePath; // 如果需要相对路径可以使用
					this.uploadImages.push(relativePath); // 用于上传到服务器
				} catch (error) {
					console.error('图片上传失败:', error);
				} finally {
					this.uploading = false;
				}
			}
		},
		onRemoveImage(index) {
			this.uploadedImages.splice(index, 1);
		},
		async onAddVideo() {
			if (!this.uploadedVideo) {
				try {
					const res = await uni.chooseVideo({
						sourceType: ['album', 'camera'],
						compressed: true
					});
					const filePath = res.tempFilePath;
					this.uploading = true;
					setTimeout(() => {
						this.uploading = false;
					}, 1000); // 模拟上传进度
					const uploadRes = await uni.uploadFile({
						url: 'api/recruit-fileUpload/files/upload',
						filePath,
						name: 'file'
					});
					// 获取返回数据
					const response = JSON.parse(uploadRes.data);
					this.uploadedVideo = response.url; // 用于展示完整视频地址
					const relativePath = response.relativePath; // 如果需要相对路径可以使用
					this.uploadVideo = relativePath; // 用于上传到服务器
				} catch (error) {
					console.error('视频上传失败:', error);
				} finally {
					this.uploading = false;
				}
			}
		},
		onRemoveVideo() {
			this.uploadedVideo = '';
		},
		onPreviewImage(index) {
			// 图片预览逻辑
			uni.previewImage({
				current: this.uploadedImages[index], // 当前预览的图片
				urls: this.uploadedImages // 所有图片的URL数组
			});
		}
	},
	onLoad(options) {
		this.dynamicType = options.dynamicType || 'article';
	}
};
</script>

<style scoped>
@import '@/static/remixicon.css';

.edit-container {
	padding-top: 60px;
}
.top-bar {
	background-color: #59a0ff;
	padding: 10px;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
}
.top-bar-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.back-icon {
	font-size: 24px;
	color: white;
	cursor: pointer;
}
.edit-title {
	color: white;
	font-size: 18px;
	font-weight: bold;
}
.publish-button {
	background-color: white;
	margin: 0;
	color: #59a0ff;
	border: none;
	border-radius: 15px;
	font-size: 16px;
	cursor: pointer;
}
.content {
	padding: 20px;
}
.content-title {
	font-size: 20px;
	font-weight: bold;
	margin-bottom: 10px;
}
.content-textarea {
	width: 95%;
	height: 150px;
	border: 1px solid #e0e0e0;
	border-radius: 10px;
	padding: 10px;
	font-size: 16px;
	outline: none;
	resize: none;
}
.char-counter {
	text-align: right;
	font-size: 14px;
	color: #999;
	margin-top: 5px;
}
.upload-section {
	margin-top: 20px;
}
.upload-button {
	background-color: #59a0ff;
	height: 50rpx;
	color: white;
	padding: 10px;
	border: none;
	border-radius: 10px;
	display: flex;
	align-items: center;
	cursor: pointer;
}
.upload-button.light-grey-button {
	background-color: #f0f0f0;
	color: #666;
}
.upload-button i {
	margin-right: 5px;
}
.image-grid {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 10px;
	margin-top: 10px;
}
.image-item {
	position: relative;
	width: 100%;
	padding-bottom: 100%;
}
.add-image-button {
	width: 100%;
	height: 150px;
	background-color: #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 10px;
	cursor: pointer;
}
.add-image-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	color: #666;
}
.add-icon {
	font-size: 24px;
}
.add-text {
	font-size: 14px;
	margin-top: 5px;
	color: #666;
}
.uploaded-image {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	object-fit: cover;
	border-radius: 10px;
}
.remove-icon {
	position: absolute;
	top: -5px;
	right: -5px;
	font-size: 18px;
	color: red;
	cursor: pointer;
}
.video-item {
	position: relative;
	margin-top: 20px;
	width: 70%;
	aspect-ratio: 16/9;
}
.uploaded-video {
	width: 100%;
	height: 100%;
	border-radius: 10px;
}
</style>
